package dialogos;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.DefaultCellEditor;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ScrollPaneConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

import accesoADatos.AccesoADatos;
import datos.Cliente;

public class EmailsDialog extends JDialog {
	
	private JTable table;
	private JTextArea textArea;
	private JTextArea textArea_1;
	private JTextField textField;
	private JLabel lblAsunto;
	
	public EmailsDialog(JFrame frame) {
		super(frame, true);
		initGUI();
	}

	private void initGUI() {
		this.setTitle("Enviar Mail");
		this.setPreferredSize(new Dimension(450,350));
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setPreferredSize(new Dimension(150,300));
		DefaultTableModel model = new DefaultTableModel(new Object[][] {}, new String[] {"Cliente", ""}){
			public Class getColumClass (int columnIndex){
				if(columnIndex == 0)
					return Cliente.class;
				return Boolean.class;
			}
			
			public boolean isCellEditable(int rowIndex, int columnIndex){
				if(columnIndex == 1)
					return true;
				return false;
			}
		};
		List clientes = AccesoADatos.getInstance().getClientes();
		Vector v;
		for(int i=0; i<clientes.size(); i++){
			v = new Vector();
			v.add(clientes.get(i));
			v.add(new Boolean(false));
			model.addRow(v);
		}
		table = new JTable(model);
		scrollPane.setViewportView(table);
		JCheckBox jcb = new JCheckBox();
		jcb.setHorizontalAlignment(JLabel.CENTER);
		table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(jcb));
		table.getColumnModel().getColumn(1).setCellRenderer(new TableCellRenderer(){
				private JCheckBox check;
			@Override
			public Component getTableCellRendererComponent(JTable arg0,
					Object arg1, boolean arg2, boolean arg3, int arg4, int arg5) {
				check = new JCheckBox();
				check.setSelected((Boolean)arg1);
				check.setHorizontalAlignment(JLabel.CENTER);
				return check;
			}
		});
		table.setPreferredScrollableViewportSize(new Dimension(200,200));
		table.getColumnModel().getColumn(1).setMaxWidth(30);
		table.getColumnModel().getColumn(1).setMinWidth(30);
		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scrollPane_1.setPreferredSize(new Dimension(250,300));
		
		textArea = new JTextArea();
		textArea.setRows(20);
		textArea.setColumns(15);
		textArea.setLineWrap(true);
		scrollPane_1.setViewportView(textArea);
		
		JPanel panel = new JPanel();
		
		JPanel panel_1 = new JPanel();
		
		JScrollPane scrollPane_2 = new JScrollPane();
		
		lblAsunto = new JLabel("Asunto:");
		
		textField = new JTextField();
		textField.setColumns(10);
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(panel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(scrollPane, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
						.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
						.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
							.addComponent(lblAsunto)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(textField, GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE))
						.addComponent(panel_1, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
						.addComponent(scrollPane_2, GroupLayout.PREFERRED_SIZE, 201, GroupLayout.PREFERRED_SIZE))
					.addGap(0))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 246, GroupLayout.PREFERRED_SIZE)
						.addGroup(groupLayout.createSequentialGroup()
							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblAsunto)
								.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(scrollPane_1, GroupLayout.PREFERRED_SIZE, 160, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(scrollPane_2, GroupLayout.PREFERRED_SIZE, 60, GroupLayout.PREFERRED_SIZE)))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 156, GroupLayout.PREFERRED_SIZE)
						.addComponent(panel, GroupLayout.PREFERRED_SIZE, 156, GroupLayout.PREFERRED_SIZE))
					.addContainerGap())
		);
		
		textArea_1 = new JTextArea();
		scrollPane_2.setViewportView(textArea_1);
		
		JButton btnDeseleccionarTodos = new JButton("Desmarcar Todos");
		btnDeseleccionarTodos.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				for(int i=0; i<EmailsDialog.this.table.getRowCount(); i++){
					EmailsDialog.this.table.setValueAt(new Boolean(false), i, 1);
				}
			}
		});
		
		JButton btnSeleccionarTodos = new JButton("Marcar Todos");
		btnSeleccionarTodos.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				for(int i=0; i<EmailsDialog.this.table.getRowCount(); i++){
					EmailsDialog.this.table.setValueAt(new Boolean(true), i, 1);
				}
			}
		});
		panel.add(btnSeleccionarTodos);
		panel.add(btnDeseleccionarTodos);
		
		JButton btnAdjuntar = new JButton("Adjuntar...");
		panel_1.add(btnAdjuntar);
		
		JButton btnEnviar = new JButton("Enviar");
		btnEnviar.addActionListener(new ActionListener() {
			private String email;
			private String password;
			private String smtp;
			private String puerto;

			public void actionPerformed(ActionEvent e) {
				Properties p = new Properties();
				email = "";
				password = "";
				smtp = "";
				puerto = "";
				try {
					FileInputStream fis = new FileInputStream("propiedades.properties");
					p.load(fis);
					email = p.getProperty("email");
					password = p.getProperty("emailpass");
					smtp = p.getProperty("smtp");
					puerto = p.getProperty("puerto");
					fis.close();
				} catch (FileNotFoundException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				} catch (IOException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}
				
				Properties props = new Properties();
				props.put("mail.smtp.host", smtp);
				props.setProperty("mail.smtp.starttls.enable", "true");
				props.setProperty("mail.smtp.port",puerto);
				props.setProperty("mail.smtp.user", email);
				props.setProperty("mail.smtp.auth", "true");
				//props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
				Session session = Session.getDefaultInstance(props, null/*new Authenticator(){
					protected PasswordAuthentication getPasswordAuthentication(){
						return new PasswordAuthentication(email, password);
					}
				}*/);
				session.setDebug(false);
				
				BodyPart texto = new MimeBodyPart();
				try {
					texto.setText(EmailsDialog.this.textArea.getText());
				} catch (MessagingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				MimeMultipart multiParte = new MimeMultipart();
				try {
					multiParte.addBodyPart(texto);
				} catch (MessagingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				MimeMessage message = new MimeMessage(session);
				
				try {
					
					message.setFrom(new InternetAddress(email));
					String mail;
					for(int i=0; i<EmailsDialog.this.table.getRowCount(); i++){
						mail = ((Cliente)EmailsDialog.this.table.getValueAt(i, 0)).getEmail();
						if(mail != null && !mail.equals(""))
							message.addRecipient(Message.RecipientType.BCC, new InternetAddress(((Cliente)EmailsDialog.this.table.getValueAt(i, 0)).getEmail()));
					}
					message.setSubject(EmailsDialog.this.textField.getText());
					message.setContent(multiParte);	
					Transport t = session.getTransport("smtp");
					t.connect(email, password);
					t.sendMessage(message,message.getAllRecipients());
					t.close();
					JOptionPane.showMessageDialog(EmailsDialog.this, "Los mensajes se enviaron corretamente.", "Mensajes Enviados", JOptionPane.INFORMATION_MESSAGE);
				} catch (AddressException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (MessagingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					JOptionPane.showMessageDialog(EmailsDialog.this, "Ha ocurrido un error mientras se enviaba los mensajes.\nLos mensajes no fueron enviados.", "Error", JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		panel_1.add(btnEnviar);
		getContentPane().setLayout(groupLayout);
		pack();
		this.setLocationRelativeTo(null);
		this.setVisible(true);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new EmailsDialog(new JFrame()).setVisible(true);
	}
}
